import { RoutesMap, allRoutes, routes } from '@/router/routes';
import { filterAsyncRouter } from '@/utils/permission';
import { defineStore } from 'pinia';
import { Ref, markRaw, ref, watchEffect } from 'vue';

export const UPDATE = 0b0001;
export const DELETE = 0b0010;
export const ADD = 0b0100;
const admin = UPDATE | DELETE | ADD;
const user = admin & ~ADD;

export const userStore = defineStore('user', () => {
  const roleName = ref('user');
  const routers = ref<RoutesMap[]>([]);
  const userInfo = ref<any>({ permissions: '' });
  watchEffect(() => {
    if (roleName.value === 'admin') {
      userInfo.value.permissions = admin;
    } else {
      userInfo.value.permissions = user;
    }
  });
  const setUserPermissions = (permissions: string) => {
    // 设置用户权限
    roleName.value = permissions;
  };

  const handleRoutes = () => {
    const router = markRaw(allRoutes);
    const accessedRoutes = filterAsyncRouter(router, roleName.value);
    routers.value = accessedRoutes;
  };

  return { userInfo, setUserPermissions, roleName, handleRoutes, routers };
});
